package com.heima.wemedia.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.stream.StreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.dtos.PageResponseResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.CustomException;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.utils.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
        @Resource
        private WmMaterialMapper wmMaterialMapper;
        @Resource
        private WmNewsMaterialMapper wmNewsMaterialMapper;
    /**
     * 查询文章
     */
    @Override
    public ResponseResult<List<WmNews>> findAll(WmNewsPageReqDto dto) {
        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页参数检查
        dto.checkParam();
        //获取当前登录人的信息
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2.分页条件查询
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = Wrappers.<WmNews>lambdaQuery()
                .eq(ObjectUtil.isNotEmpty(dto.getStatus()), WmNews::getStatus, dto.getStatus()) //状态精确查询
                .eq(ObjectUtil.isNotEmpty(dto.getChannelId()), WmNews::getChannelId, dto.getChannelId()) //频道精确查询
                .between(ObjectUtil.isAllNotEmpty(dto.getBeginPubDate(), dto.getEndPubDate()), WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate())  //时间范围查询
                .like(ObjectUtil.isNotEmpty(dto.getKeyword()), WmNews::getTitle, dto.getKeyword()) //关键字模糊查询
                .eq(WmNews::getUserId, user.getId()) //查询当前登录用户的文章
                .orderByDesc(WmNews::getCreatedTime) //发布时间倒序查询
                ;
        //分页查询
        page(page, lambdaQueryWrapper);

        //3.结果返回
        return PageResponseResult.<List<WmNews>>builder()
                .size(dto.getSize())
                .currentPage(dto.getPage())
                .total(dto.getPage())
                .size(Convert.toInt(page.getTotal()))
                .data(page.getRecords())
                .build();
    }

    /**
     * 发布修改文章或保存为草稿
     */
    @Override
    public ResponseResult<Object> submitNews(WmNewsDto dto) {
        //0.条件判断
        if (ObjectUtil.isEmpty(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //1.保存或修改文章
        WmNews wmNews = BeanUtil.toBean(dto, WmNews.class);
        //封面图片  list---> string
        if (CollUtil.isNotEmpty(dto.getImages())) {
            //[1dddfsd.jpg,sdlfjldk.jpg]-->   1dddfsd.jpg,sdlfjldk.jpg
            String imageStr = StrUtil.join(",", dto.getImages());
            wmNews.setImages(imageStr);
        }
        //如果当前封面类型为自动 -1
        if (ObjectUtil.equal(dto.getType(), WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }

        //保存或更新数据
        saveOrUpdateWmNews(wmNews);

        //2.判断是否为草稿  如果为草稿结束当前方法
        if (ObjectUtil.equal(dto.getStatus(), WmNews.Status.NORMAL.getCode())) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //3.不是草稿，保存文章内容图片与素材的关系
        //获取到文章内容中的图片信息
        List<String> materials = extractUrlInfo(dto.getContent());
        saveRelativeInfoForContent(materials, wmNews.getId());

        //4.不是草稿，保存文章封面图片与素材的关系，如果当前布局是自动，需要匹配封面图片
        saveRelativeInfoForCover(dto, wmNews, materials);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    /**
     * 第一个功能：如果当前封面类型为自动，则设置封面类型的数据
     * 匹配规则：
     * 1，如果内容图片大于等于1，小于3  单图  type 1
     * 2，如果内容图片大于等于3  多图  type 3
     * 3，如果内容没有图片，无图  type 0
     * <p>
     * 第二个功能：保存封面图片与素材的关系
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
        List<String> images = dto.getImages();
        //如果当前封面类型为自动，则设置封面类型的数据
        if (ObjectUtil.equal(dto.getType(), WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            if (CollUtil.isEmpty(materials)) {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            } else if (CollUtil.size(materials) >= 3) {
                //多图
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = CollUtil.sub(materials, 0, 3);
            } else {
                //单图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = CollUtil.sub(materials, 0, 1);
            }

            //修改文章
            if (CollUtil.isNotEmpty(images)) {
                wmNews.setImages(StrUtil.join(",", images));
            }
            super.updateById(wmNews);
        }
        if (CollUtil.isNotEmpty(images)) {
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);
        }
    }


    /**
     * 处理文章内容图片与素材的关系
     */
    private void saveRelativeInfoForContent(List<String> materials, Integer newsId) {
        saveRelativeInfo(materials, newsId, WemediaConstants.WM_CONTENT_REFERENCE);
    }


    /**
     * 保存文章图片与素材的关系到数据库中
     */
    private void saveRelativeInfo(List<String> materials, Integer newsId, Short type) {
        if (CollUtil.isEmpty(materials)) {
            return;
        }
        //通过图片的url查询素材的id
        List<WmMaterial> dbMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials));

        //判断素材是否有效
        if (CollUtil.isEmpty(dbMaterials)) {
            //手动抛出异常   第一个功能：能够提示调用者素材失效了，第二个功能，进行数据的回滚
            throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
        }

        if (materials.size() != dbMaterials.size()) {
            throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
        }

        List<Integer> idList = CollStreamUtil.toList(dbMaterials, WmMaterial::getId);

        //批量保存
        wmNewsMaterialMapper.saveRelations(idList, newsId, type);
    }


    /**
     * 提取文章内容中的图片信息
     */
    private List<String> extractUrlInfo(String content) {
        return StreamUtil.of(JSONUtil.toList(content, JSONObject.class))
                .filter(jsonObject -> StrUtil.equals(jsonObject.getStr("type"), "image"))
                .map(jsonObject -> jsonObject.getStr("value"))
                .collect(Collectors.toList());
    }

    /**
     * 保存或修改文章
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        if (ObjectUtil.isEmpty(wmNews.getId())) {
            //补全属性
            wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
            wmNews.setCreatedTime(new Date());
            wmNews.setSubmitedTime(new Date());
            wmNews.setEnable((short) 1);//默认上架
            //保存
            super.save(wmNews);
            return;
        }
        //删除文章图片与素材的关系
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId());
        this.wmNewsMaterialMapper.delete(queryWrapper);
        //修改数据
        super.updateById(wmNews);
    }



}
